@echo off
setlocal enabledelayedexpansion
chcp 65001 >nul

echo ===== Teacher Info System Database Backup Script (Windows) =====
echo.

REM Configuration parameters
set DB_HOST=119.3.213.163
set DB_PORT=3306
set DB_NAME=teacher_info_system
set DB_USER=root
set DB_PASSWORD=cjx12345@

REM Generate timestamp
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~2,2%" & set "YYYY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%"
set "HH=%dt:~8,2%" & set "Min=%dt:~10,2%" & set "Sec=%dt:~12,2%"
set "BACKUP_DATE=%YYYY%%MM%%DD%_%HH%%Min%%Sec%"

REM Backup file path
set BACKUP_DIR=database_backup
set BACKUP_FILE=%BACKUP_DIR%\teacher_info_system_backup_%BACKUP_DATE%.sql

REM Create backup directory
if not exist %BACKUP_DIR% mkdir %BACKUP_DIR%

echo Starting database backup...
echo Source database: %DB_HOST%:%DB_PORT%/%DB_NAME%
echo Backup file: %BACKUP_FILE%
echo.

REM Check if mysqldump is available
mysqldump --version >nul 2>&1
if %errorlevel% neq 0 (
    echo Error: mysqldump command not found
    echo.
    echo Please install MySQL Client or ensure mysqldump is in system PATH
    echo Download: https://dev.mysql.com/downloads/mysql/
    echo.
    pause
    exit /b 1
)

REM Execute database backup
echo Backing up database, please wait...
mysqldump -h%DB_HOST% -P%DB_PORT% -u%DB_USER% -p%DB_PASSWORD% ^
    --single-transaction ^
    --routines ^
    --triggers ^
    --events ^
    --set-gtid-purged=OFF ^
    --default-character-set=utf8mb4 ^
    --add-drop-table ^
    --create-options ^
    --disable-keys ^
    --extended-insert ^
    --quick ^
    --lock-tables=false ^
    %DB_NAME% > %BACKUP_FILE%

REM Check if backup was successful
if %errorlevel% equ 0 (
    echo Database backup successful!
    
    REM Display file size
    for %%A in (%BACKUP_FILE%) do (
        set size=%%~zA
        set /a sizeKB=!size!/1024
        set /a sizeMB=!sizeKB!/1024
        echo Backup file size: !sizeMB! MB
    )
    
    REM Verify backup file
    echo Verifying backup file integrity...
    findstr /C:"MySQL dump" %BACKUP_FILE% >nul
    if !errorlevel! equ 0 (
        echo Backup file verification successful!
    ) else (
        echo Backup file may be corrupted, please check!
        pause
        exit /b 1
    )
    
) else (
    echo Database backup failed! Please check connection parameters and permissions.
    echo.
    echo Possible causes:
    echo 1. Network connection issues
    echo 2. Database server unreachable
    echo 3. Incorrect username or password
    echo 4. Insufficient permissions
    echo.
    pause
    exit /b 1
)

echo.
echo ===== Backup Complete =====
echo Backup file: %BACKUP_FILE%
echo.
echo Next steps:
echo 1. Upload backup file to target server
echo 2. Execute data recovery script on server
echo.
echo Upload command example:
echo scp %BACKUP_FILE% root@your-server:/opt/teacher-system/database_backup/
echo.
pause
